"""
    Created by 范钟<coder.zf@outlook.com> on 2019/04/08
"""
from flask import request, render_template, redirect, url_for, flash, get_flashed_messages

from forms.auth import RegisterForm, LoginForm
from models.base import db
from models.user import User
from flask_login import login_user
from . import web


@web.route("/register", methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User()
        user.set_attrs(form.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("web.login"))

    return render_template('auth/register.html', form=form)


@web.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            # remember 设置持续存储cookie时间（默认为365天）
            login_user(user, remember=True)
            next = request.args.get('next', '/')
            return redirect(next)
        else:
            flash("账号不存在或者密码错误")
            print(get_flashed_messages())

    return render_template("auth/login.html", form=form)


@web.route('/forget_password_request')
def forget_password_request():
    pass
